from selenium.common import NoSuchElementException

from framwork.pages.base_page import BasePage
from selenium.webdriver.common.by import By


class AddLogPage(BasePage):
    url = '/crm/index.php?m=log&a=mylog_add'
    # === 3. 元素定位器（集中管理，便于维护） ===
    input_log_title_locator = (By.NAME, 'subject')  # 日志标题
    input_log_content_locator = (By.CLASS_NAME, 'ke-content')  # 日志内容
    iframe_log_content_locator = (By.CLASS_NAME, "ke-edit-iframe")  # 日志内容所在iframe
    btn_save_locator = (By.NAME, 'submit')  # 保存按钮
    success_tips_locator = (By.CLASS_NAME, "alert-success")  # 添加日志成功
    fail_tips_locator = (By.CLASS_NAME, 'alert-error')  # 日志标题不能为空
    fail_illegal_tips_locator = (By.CSS_SELECTOR, 'body > div.container > form > fieldset > legend > h3')  # 非法内容

    def input_log_title(self, log_title):
        """日志标题输入"""
        self.send_keys(self.input_log_title_locator, log_title)

    def input_log_content(self, log_content):
        """日志内容输入"""
        iframe = self.find_element(self.iframe_log_content_locator)
        self.switch_to_frame(iframe)
        # 定位日志内容输入框
        self.send_keys(self.input_log_content_locator, log_content)
        # 切回默认frame
        self.switch_to_default()

    def click_save_button(self):
        """点击日志保存"""
        self.click(self.btn_save_locator)

    def add_log(self, log_title, log_content):
        """添加日志的封装方法"""
        self.input_log_title(log_title)
        self.input_log_content(log_content)
        self.click_save_button()

    def get_success_tips(self):
        """获取添加成功的信息"""
        try:
            success_text = self.find_element(self.success_tips_locator).text
        except NoSuchElementException:
            success_text = ""
        return success_text

    def get_fail_tips(self):
        """获取添加失败的信息"""
        try:
            fail_text = self.find_element(self.fail_tips_locator).text
        except NoSuchElementException:
            fail_text = ""
        return fail_text

    def get_fail_illegal_tips(self):
        """获取添加非法失败的信息"""
        try:
            fail_illegal_text = self.find_element(self.fail_illegal_tips_locator).text
        except NoSuchElementException:
            fail_illegal_text = ""
        return fail_illegal_text
